function Database(file) 
{
	if (file !== undefined) {
		//openDatabase takes an nsIFile
		this._ds = Database.sql.openDatabase(file);
	}
	else {
		this._ds = Database.sql.openSpecialDatabase("memory");
	}
	
	if (this.dsAvailable()) {
		this._ds.executeSimpleSQL("PRAGMA synchronous = OFF")
		this._ds.createTable("IF NOT EXISTS Day", "date TEXT NOT NULL PRIMARY KEY, duration INTEGER");
		this._ds.createTable("IF NOT EXISTS Session", "siteId TEXT, date TEXT, duration INTEGER, PRIMARY KEY (siteId, date)");
	}
}

Database.SQLSERVICE_CID = "@mozilla.org/storage/service;1";
Database.sql = CC[Database.SQLSERVICE_CID].getService(CI.mozIStorageService);

Database.prototype.dsAvailable = function() {
	if (this._ds)
		return this._ds.connectionReady;
	else
		return false;
}

Database.prototype._getDuration = function DB__getDuration(siteId, date) 
{
	var duration = 0;
	var statement;
	
	if (siteId !== null)
		statement = this._ds.createStatement
			("SELECT duration FROM Session WHERE date=='" + date + "' AND siteId=='" + siteId + "'");
	else
		statement = this._ds.createStatement
			("SELECT duration FROM Day WHERE date=='" + date + "'");
	
	try {
		statement.executeStep();
		duration = statement.getInt32(0);
	}
	catch(e) { /* do nothing */
	}		
	finally { 
		statement.reset(); 
	} 
	
	return duration;
}

Database.prototype._updateDuration = function DB__updateDuration(siteId, date, duration) 
{	
	var statement;
	if (siteId !== null)
		statement = this._ds.createStatement
			("INSERT OR REPLACE INTO Session VALUES ('" + siteId + "','" + date + "'," + duration + ")");
	else
		statement = this._ds.createStatement
			("INSERT OR REPLACE INTO Day VALUES ('" + date + "'," + duration + ")");
			
	statement.execute();
}

Database.prototype.getSessionDuration = function DB_getSessionDuration(siteId, date)
{
	return this._getDuration(siteId, date);
}

Database.prototype.updateSessionDuration = function DB_updateSessionDuration(siteId, date, duration)
{
	this._updateDuration(siteId, date, duration);
}

Database.prototype.getDailyTotal = function DB_getDailyTotal(date) 
{
	return this._getDuration(null, date);
}

Database.prototype.updateDailyTotal = function DB_updateDailyTotal(date, duration) 
{
	this._updateDuration(null, date, duration);
}

Database.prototype.save = function DB_save() {
}
